//
//  AssigningViewController.m
//  UEAssistant
//
//  Created by mac on 2017/4/13.
//  Copyright © 2017年 youyixinxi. All rights reserved.
//

#import "AssigningViewController.h"
#import "YZPullDownMenu.h"
#import "YZMenuButton.h"
#import "SectionController.h"
#import "LanguageController.h"
#import "StarController.h"
#import "TypeController.h"
#import "TagsViewController.h"
#import "StarsView.h"
#import "TransLaterTableViewCell.h"
#import "YHXCalendarView.h"
#import "AssigningViewController.h"
#import "UIView+Utils.h"
#import "AssignModel.h"
#import "StarsView.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#define YZScreenW [UIScreen mainScreen].bounds.size.width
#define YZScreenH [UIScreen mainScreen].bounds.size.height

@interface AssigningViewController ()<YZPullDownMenuDataSource,UITableViewDataSource,UITableViewDelegate,RemarksCellDelegate,UISearchBarDelegate,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource>{

    NSMutableArray              *_cells;
    NSIndexPath                 *_selectIndexPath;
    NSMutableArray              *_dataSource;
    NSMutableArray              *_dataSource_old;
    NSMutableDictionary         *_conditions;//筛选条件数组
    NSMutableArray              *_originData;
    NSMutableArray              *_tags;
    NSInteger                   _selectedIndex_TransLater;
    BOOL                        _AlreadyAssignTransLater;
    NSInteger                   _selectTranser_static;
    NSInteger                   _selectUserId;
}

@property (nonatomic, strong) NSArray   *titles;//下拉菜单的标题
@property (nonatomic, strong) UITableView           *tableView;//译员列表
@property (nonatomic, strong) NSArray        *leves;
@property (nonatomic, strong) NSMutableDictionary *cellIsShowAll;// 存放cell视图展开状态的字典
@property (nonatomic, strong) NSArray *types;
@property (nonatomic, strong) UIButton          *endTime;
@property (nonatomic, strong) UIButton          *assignTask;
@property (nonatomic, strong) UIView            *line;
@property (nonatomic, strong) UIView            *coverView;
@property (nonatomic, strong) UILabel           *endTimeLabel;
@property (nonatomic, assign) BOOL              hasEndTime;
@property (nonatomic, strong) UISearchBar       *searchBar;
@property (nonatomic, strong) NSMutableArray    *showMore_indexPath_array;
@property (nonatomic, strong) YZPullDownMenu    *menu;
@property (nonatomic, strong) NSIndexPath       *lastPath;//记录上次选中的cell
@property (nonatomic, strong) StarsView         *starView;
@property (nonatomic, assign) BOOL              hasPrefix;//判断是否有语言对
@property (nonatomic, strong) NSString          *endtimePost;
@property (nonatomic, assign) NSInteger         userId_threeType;
@property (nonatomic, strong) UILabel           *endTimeSub;
@property (nonatomic, assign) BOOL              isSearchData;
@property (nonatomic, assign) BOOL              notSelectAssign;
@property (nonatomic, strong) NSString         *otherTransId;


@end

@implementation AssigningViewController

- (void)dealloc{

    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"hideCover" object:nil];
}

- (void)viewWillAppear:(BOOL)animated{

}

- (void)viewWillDisappear:(BOOL)animated{

    [_searchBar removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initlizeuserface];
    [self initlizeDataSource];
}

- (void)initlizeuserface{

    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self setExtraCellLineHidden:self.tableView];
    
    [self.view addSubview:self.endTime];
    [self.view addSubview:self.assignTask];
    [self.view addSubview:self.line];
    
    // 创建下拉菜单
    _menu = [[YZPullDownMenu alloc] init];
    _menu.frame = CGRectMake(0, 0, YZScreenW, 44);
    [self.view addSubview:_menu];
    _menu.dataSource = self;
    _titles = @[@"分组",@"语言",@"星级",@"类型",@"标签"];
    [self setupAllChildViewController];
    
    [self.view addSubview:self.coverView];
    
    [self creatSearchTextField];
    [self juddgeIsAssignTranslater];
}

- (void)initlizeDataSource{
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hideCoverCliced:) name:@"hideCover" object:nil];
    _leves = @[@"2",@"3",@"5",@"2",@"1",@"4",@"2",@"3",@"5",@"2",@"1",@"4"];
    _cellIsShowAll = [NSMutableDictionary dictionary];
    _cells = [NSMutableArray array];
    _showMore_indexPath_array = [NSMutableArray array];
    _dataSource = [NSMutableArray array];
    _dataSource_old = [NSMutableArray array];
    _conditions = [NSMutableDictionary dictionary];
    _originData = [@[] mutableCopy];
    _tags = [@[] mutableCopy];
    _selectedIndex_TransLater = -1;
    _lastPath = [NSIndexPath indexPathForRow:-1 inSection:0];
    _otherTransId = @"-1";

    [AvailableNetWorking postWithUrl:TeamTranslaters_connector params:@{@"teamId":self.owner_id} successHandler:^(id responseObject) {
       
        NSLog(@"-----%@",responseObject);
        if ([responseObject[@"code"] integerValue] == 200) {

            for (int i = 0; i < ((NSArray *)(responseObject[@"result"])).count; i++) {
                NSDictionary *dic = responseObject[@"result"][i];
                AssignModel *model = [[AssignModel alloc]initWithDictionary:dic];
                model.flag = i;
                [_dataSource addObject:model];
                [_originData addObject:model];
            }
            
            //缓存全部本地数据
            [_dataSource_old addObjectsFromArray:_dataSource];
            [self.tableView reloadData];
            
            switch ([self.userType integerValue]) {
                case 1:
                    _userId_threeType = [self.trans_userId integerValue];
                    _selectTranser_static = [self.trans_userId integerValue];
                    break;
                case 2:
                    _userId_threeType = [self.edit_userId integerValue];
                    _selectTranser_static = [self.edit_userId integerValue];
                    break;
                case 3:
                    _userId_threeType = [self.pro_userId integerValue];
                    _selectTranser_static = [self.pro_userId integerValue];
                    break;
                default:
                    break;
            }
            NSLog(@" userIdAll == %ld",(long)_userId_threeType);
            [_dataSource enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
               
                if ([((AssignModel *)obj).userId integerValue] == _userId_threeType) {
                    _selectedIndex_TransLater = idx;
                    _lastPath = [NSIndexPath indexPathForRow:_selectedIndex_TransLater inSection:0];
                    _AlreadyAssignTransLater = YES;
                    ((AssignModel *)obj).isSelected = YES;//记录指派过的译员
                }
            }];
            
            //默认限制语言方向
            [_conditions setObject:@"限制语言方向" forKey:@"language"];
            [self filterByConditios];
            
        }else{
        
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];

        }
        
    } falureHandler:^(NSError *error) {
        
    }];
}

- (void)juddgeIsAssignTranslater{

    if (![self.compelateTime isEqualToString:@""] && ![self.compelateTime isEqualToString:@"(null)"] && !_AlreadyAssignTransLater) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            _endtimePost = self.compelateTime;
            [self.endTime setTitleEdgeInsets:UIEdgeInsetsMake(-13, 0, 0, 0)];
            self.endTime.titleLabel.font = [UIFont systemFontOfSize:FLEXIBLE(12)];
            self.endTimeSub.text = [NSString stringWithFormat:@"%@",self.compelateTime];
            [self.endTime addSubview:self.endTimeSub];
            _hasEndTime = YES;
        });

    }
}

- (void)creatSearchTextField{

    _searchBar=[[UISearchBar alloc] initWithFrame:CGRectMake(35*Radio, 6, Screen_Width-35*Radio - 25*Radio, 30*Radio)];
    [_searchBar setSearchBarStyle:UISearchBarStyleDefault];
    _searchBar.tintColor = [UIColor grayColor];
    [_searchBar setPlaceholder:@"搜索译员（团队昵称）"];
    
    _searchBar.delegate = self;
    [_searchBar setImage:[UIImage imageNamed:@"search"]
            forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    [self.navigationController.navigationBar addSubview:_searchBar];
    
    UITextField *searchField = [self.searchBar valueForKey:@"searchField"];
    if (searchField) {
        
        searchField.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.2];
        [searchField setValue:[UIColor colorWithWhite:0.3 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
        searchField.textColor = RGB(51, 51, 51, 1) ;
        searchField.tintColor = [UIColor whiteColor];
    }
    
    UIView* backgroundView = [_searchBar subViewOfClassName:@"_UISearchBarSearchFieldBackgroundView"];
    backgroundView.layer.cornerRadius = 14*Radio;
    backgroundView.layer.masksToBounds = YES;

}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
    for(id cc in [searchBar subviews])
    {
        for (UIView *view in [cc subviews]) {
            if ([NSStringFromClass(view.class) isEqualToString:@"UINavigationButton"])
            {
                UIButton *btn = (UIButton *)view;
                [btn setTitle:@"取消" forState:UIControlStateNormal];
                [btn setTitleColor:RGB(51, 51, 51, 1) forState:UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:FLEXIBLE(16)];
            }
        }
    }
    
}


#pragma mark - 添加子控制器&&使用block回调选择的类型 
- (void)setupAllChildViewController{
    
//分组筛选控制器
    SectionController   *secVC  = [[SectionController alloc] init];
    secVC.didSelectSectionHandler = ^(NSString* type){

        if ([type isEqualToString:@"分组"]) {
            [_conditions removeObjectForKey:@"section"];
        }else{
            [_conditions setObject:type forKey:@"section"];
        }
        [self filterByConditios];
    };

//语言筛选控制器
    LanguageController  *langVC = [[LanguageController alloc] init];
    langVC.didSelectSectionHandler = ^(NSString *type){
    
        if ([type isEqualToString:@"限制语言方向"]) {
            [_conditions setObject:type forKey:@"language"];
            
        }else{
            [_conditions removeObjectForKey:@"language"];
        }
        [self filterByConditios];

    };
    
//星级筛选控制器
    StarController      *starVC = [[StarController alloc] init];
    starVC.didSelectSectionHandler = ^(NSString* type){
        
        if ([type isEqualToString:@"不限"]) {
            [_conditions removeObjectForKey:@"stars"];
            
        }else{
            [_conditions setObject:type forKey:@"stars"];
        }
        [self filterByConditios];

    };
    
//工作类型筛选控制器
    TypeController      *typeVC = [[TypeController alloc] init];
    typeVC.didSelectSectionHandler = ^(NSString *type){
    
        if ([type isEqualToString:@"不限"]) {
            [_conditions removeObjectForKey:@"workType"];
            
        }else{
            [_conditions setObject:type forKey:@"workType"];
        }
        [self filterByConditios];

    };
    
//标签筛选控制器
    TagsViewController  *tagVC  = [[TagsViewController alloc]init];
    tagVC.didSelectSectionHandler = ^(NSString *tag){
    
        if (tag) {
            if ([tag isEqualToString:@"重置"]) {
                [_tags removeAllObjects];
            }else{
                [_tags addObject:tag];
            }
        }
        if (_tags.count == 0) {
            [_conditions removeObjectForKey:@"tags"];
            
        }else{
            [_conditions setObject:_tags forKey:@"tags"];
        }
        [self filterByConditios];

    };
    
//添加子控制器
    [self addChildViewController:secVC];
    [self addChildViewController:langVC];
    [self addChildViewController:starVC];
    [self addChildViewController:typeVC];
    [self addChildViewController:tagVC];
}

#pragma mark -- 本地筛选
- (void)filterByConditios {
    
    NSMutableArray *filterArray = [_originData mutableCopy];
    
    if (_conditions[@"section"]) {
        NSString *gId = _conditions[@"section"];
        NSMutableArray *flag = [NSMutableArray array];
        [filterArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           
            if ([[NSString stringWithFormat:@"%@",((AssignModel *)obj).groupId] isEqualToString:gId]) {
                [flag addObject:obj];
            }
        }];
        [filterArray removeAllObjects];
        [filterArray addObjectsFromArray:flag];
    }
    if (_conditions[@"language"]) {
        NSString *languageType = [_languageType stringByReplacingOccurrencesOfString:@" - " withString:@"_"];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"languageValue CONTAINS %@", languageType];
        [filterArray filterUsingPredicate:predicate];
    }
    if (_conditions[@"stars"]) {
        NSString *star = _conditions[@"stars"];
        NSPredicate *predicate;
        if ([star isEqualToString:@"一星级"]) {
            predicate = [NSPredicate predicateWithFormat:@"star = 1"];
        }
        if ([star isEqualToString:@"二星级"]) {
            predicate = [NSPredicate predicateWithFormat:@"star = 2"];
        }
        if ([star isEqualToString:@"三星级"]) {
            predicate = [NSPredicate predicateWithFormat:@"star = 3"];
        }
        if ([star isEqualToString:@"四星级"]) {
            predicate = [NSPredicate predicateWithFormat:@"star = 4"];
        }
        if ([star isEqualToString:@"五星级"]) {
            predicate = [NSPredicate predicateWithFormat:@"star = 5"];
        }
        if (predicate) {
            [filterArray filterUsingPredicate:predicate];
        }
    }
    if (_conditions[@"workType"]) {
        NSString *workType = _conditions[@"workType"];
        NSPredicate *predicate;
        if ([workType isEqualToString:@"全职"]) {
            predicate = [NSPredicate predicateWithFormat:@"workType = 0"];
        }
        if ([workType isEqualToString:@"兼职"]) {
            predicate = [NSPredicate predicateWithFormat:@"workType = 1"];
        }
        if (predicate) {
            [filterArray filterUsingPredicate:predicate];
        }
    }
    if (((NSArray *)_conditions[@"tags"]).count > 0) {
        
        NSArray *tags = [_conditions objectForKey:@"tags"];
        NSLog(@"tags == %@",tags);
        NSMutableArray *flag = [NSMutableArray array];
        [filterArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog(@"((AssignModel *)obj).labelArr == %@",((AssignModel *)obj).labelStr);
            for (int i = 0; i < [((AssignModel *)obj).labelStr componentsSeparatedByString:@","].count; i ++) {
                if ([tags containsObject:[((AssignModel *)obj).labelStr componentsSeparatedByString:@","][i]]) {
                    if ([flag containsObject:obj]) {
                        //不添加
                    }else{
                        [flag addObject:obj];
                    }
                }
            }
        }];
        [filterArray removeAllObjects];
        [filterArray addObjectsFromArray:flag];
        
    }
    
    _dataSource = filterArray;
    [_tableView reloadData];
}


#pragma mark - YZPullDownMenuDataSource
// 返回下拉菜单多少列
- (NSInteger)numberOfColsInMenu:(YZPullDownMenu *)pullDownMenu
{
    return 5;
}

// 返回下拉菜单每列按钮
- (UIButton *)pullDownMenu:(YZPullDownMenu *)pullDownMenu buttonForColAtIndex:(NSInteger)index
{
    YZMenuButton *button = [YZMenuButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = [UIFont systemFontOfSize:FLEXIBLE(14)];
    [button setTitle:_titles[index] forState:UIControlStateNormal];
    [button setTitleColor:mainGrayColor forState:UIControlStateNormal];
    [button setTitleColor:mainColor forState:UIControlStateSelected];
    [button setImage:[UIImage imageNamed:@"标签-向下箭头"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"标签-向上箭头"] forState:UIControlStateSelected];
    return button;
}

// 返回下拉菜单每列对应的控制器
- (UIViewController *)pullDownMenu:(YZPullDownMenu *)pullDownMenu viewControllerForColAtIndex:(NSInteger)index
{
    return self.childViewControllers[index];
}

// 返回下拉菜单每列对应的高度
- (CGFloat)pullDownMenu:(YZPullDownMenu *)pullDownMenu heightForColAtIndex:(NSInteger)index
{
    if (index == 0 || index == 1) {
        if (shareData.sectiontitles == 0) {
            
            return 40;
        }else if (shareData.sectiontitles == 1){
        
            return 40;

        }else if (shareData.sectiontitles == 2){
            return 80;

        }else if (shareData.sectiontitles == 3){
            return 140;

        }else if (shareData.sectiontitles == 4){
            
            return 170;

        }else if (shareData.sectiontitles == 5){
            return 220;

        }else{
        
            return 240;
        }
    }
    else if (index == 3) {
        return 130;
    }
    else if (index == 2) {
        return 260;
    }
    else{
        return Screen_Height-64-44;
    }
}

#pragma mark -******  搜索控制器  ******-----------

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

    _isSearchData = YES;
    //搜索本地全部数据
    NSMutableArray *filterArray = [_originData mutableCopy];
    NSString *nick = searchBar.text;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nickName CONTAINS %@", nick];
    [filterArray filterUsingPredicate:predicate];
    _dataSource = filterArray;
    [self.tableView reloadData];

}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
   
    _isSearchData = NO;
    searchBar.showsCancelButton = NO;
    searchBar.text = nil;
    [searchBar resignFirstResponder];
    [self filterByConditios];
}

#pragma mark -******  解决键盘弹出导致tableview的frame变化  ******-----------


#pragma mark -- UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSString *cellName = [NSString stringWithFormat:@"meTableViewCell%ld",(long)indexPath.row];
    TransLaterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    
    if (!cell) {
        cell = [[TransLaterTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellName];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    [cell accessData:_dataSource[indexPath.row]];
    
    _starView = [[StarsView alloc]initWithFrame:CGRectMake(cell.headView.frame.origin.x+cell.headView.frame.size.width+25, cell.name.frame.origin.y+cell.name.frame.size.height+10*Radio, 90*Radio, 18*Radio) level:[((AssignModel *)_dataSource[indexPath.row]).star integerValue]];
    [cell addSubview:_starView];
    [cell starLevel:[((AssignModel *)_dataSource[indexPath.row]).star integerValue] andCellIndexPath:indexPath];

    if (((AssignModel *)_dataSource[indexPath.row]).isSelected) {
        cell.seletImage.image = [UIImage imageNamed:@"选中"];
        _lastPath = indexPath;
    }else{
        cell.seletImage.image = [UIImage imageNamed:@"选择"];
    }
    if (_AlreadyAssignTransLater) {
        [self allowToAssignTask];
    }
    
    cell.tag = 100+indexPath.row;
    [_cells addObject:cell];
    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([[self.cellIsShowAll objectForKey:[NSString stringWithFormat:@"%zd", indexPath.row]] boolValue]) {
        return 170*Radio;
    }else{
        return 90*Radio;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSInteger nowRow = [indexPath row];
    if (_AlreadyAssignTransLater) {
        
        if (!((AssignModel *)_dataSource[nowRow]).isSelected) {
            
            [_dataSource_old enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                ((AssignModel *)obj).isSelected = NO;
                TransLaterTableViewCell *lastCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
                lastCell.seletImage.image = [UIImage imageNamed:@"选择"];
            }];
            ((AssignModel *)_dataSource[nowRow]).isSelected = YES;
            TransLaterTableViewCell *nowCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:nowRow inSection:0]];
            nowCell.seletImage.image = [UIImage imageNamed:@"选中"];
            if ([((AssignModel *)_dataSource[nowRow]).userId integerValue] != _selectTranser_static) {
                [self.assignTask setTitle:@"立即换人" forState:UIControlStateNormal];
            }else{
                [self.assignTask setTitle:@"立即分派" forState:UIControlStateNormal];
            }
            _lastPath  = indexPath;
            
        }
        else{
            ((AssignModel *)_dataSource[nowRow]).isSelected = NO;
            [_dataSource_old enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                ((AssignModel *)obj).isSelected = NO;
                TransLaterTableViewCell *lastCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
                lastCell.seletImage.image = [UIImage imageNamed:@"选择"];
            }];
            [self.assignTask setTitle:@"取消任务" forState:UIControlStateNormal];
            _lastPath = [NSIndexPath indexPathForRow:-1 inSection:0];
        }

    }else{
    
        if (!((AssignModel *)_dataSource[nowRow]).isSelected) {
            
            [_dataSource_old enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                ((AssignModel *)obj).isSelected = NO;
                TransLaterTableViewCell *lastCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
                lastCell.seletImage.image = [UIImage imageNamed:@"选择"];
            
            }];
            ((AssignModel *)_dataSource[nowRow]).isSelected = YES;
            TransLaterTableViewCell *nowCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:nowRow inSection:0]];
            nowCell.seletImage.image = [UIImage imageNamed:@"选中"];
            [self.assignTask setTitle:@"立即分派" forState:UIControlStateNormal];
            _lastPath  = indexPath;
            if (_hasEndTime) {
                [self allowToAssignTask];

            }
        }
        else{
            [_dataSource_old enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                ((AssignModel *)obj).isSelected = NO;
                TransLaterTableViewCell *lastCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
                lastCell.seletImage.image = [UIImage imageNamed:@"选择"];
            }];
            [self notAllowAssignTask];
            _lastPath = [NSIndexPath indexPathForRow:-1 inSection:0];
        }
    }
}


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    

    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}


#pragma mark -- RemarksCellDelegate
- (void)remarksCellShowContrntWithDic:(NSDictionary *)dic andCellIndexPath:(NSIndexPath *)indexPath
{
    //点击显示更多后记录到数组中
    [_showMore_indexPath_array addObject:indexPath];
    [self.cellIsShowAll setObject:[dic objectForKey:@"isShow"] forKey:[NSString stringWithFormat:@"%@",[dic objectForKey:@"row"]]];
    [self.tableView reloadData];
}

#pragma mark  Event

- (void)endTimeClicked{

    YHXCalendarView *view = [[YHXCalendarView alloc]initWithFrame:CGRectMake(0, Screen_Height-64, Screen_Width, 0)];
    [self.view addSubview:view];

    [UIView animateWithDuration:0.2 animations:^{
        
        CGRect frame = CGRectMake(0, 50, Screen_Width, Screen_Height-114);
        view.frame = frame;
        self.coverView.frame = CGRectMake(0, 0, Screen_Width, 50);
        
    } completion:^(BOOL finished) {
        
    }];

}

- (void)assignTaskClicked:(UIButton *)sender{

    if ([sender.titleLabel.text isEqualToString:@"立即分派"] || [sender.titleLabel.text isEqualToString:@"立即换人"]) {
        
        NSString *str = @"end_rownum";
        NSDictionary *dic = @{@"transDocId":self.transDocId,
                              @"transBlockId":self.transBlockId,
                              @"transDocName":self.transDocName,
                              @"userType":self.userType,
                              @"userId":[NSString stringWithFormat:@"%@",((AssignModel *)_dataSource[_lastPath.row]).userId],
                              @"completeDate":_endtimePost,
                              @"projectId":shareData.product_Id,
                              @"teamId":shareData.team_Id,
                              str:self.end_rownum};
        
        NSLog(@"res ------------- %@",dic);
        [AvailableNetWorking postWithUrl:assignTask_connector params:dic successHandler:^(id responseObject) {
            
            NSLog(@"%@",responseObject[@"message"]);
            if ([responseObject[@"code"] integerValue] == 200) {
                //退栈并通知刷新上一个界面
                [self.navigationController popViewControllerAnimated:YES];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"AssignTaskSuccessAndRef" object:nil];
            }else{
        
                [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"操作失败" andTitleColor:[UIColor whiteColor] andCancel:NO];
            }
            
        } falureHandler:^(NSError *error) {
            
            NSLog(@"%@",error);
        }];

    }else if ([sender.titleLabel.text isEqualToString:@"取消任务"]){
    
        switch ([self.userType integerValue]) {
            case 1:
            {
                if ([self.edit_userId integerValue] != 0) {
                    [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"分配过编辑或校对任务，无法取消翻译任务" andTitleColor:[UIColor whiteColor] andCancel:NO];

                    }else{
                    [self cancelAssignRequest];
                }

            }
                break;
            case 2:
            {
                if ([self.pro_userId integerValue] != 0) {
                    [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"分配过校对任务，无法取消编辑任务" andTitleColor:[UIColor whiteColor] andCancel:NO];

                }else{
                    [self cancelAssignRequest];
                }
            }
                break;
            case 3:
            {
                [self cancelAssignRequest];
            }
                break;
            default:
                break;
        }
    }
}

#pragma mark -- cancelAssign

- (void)cancelAssignRequest{

    NSString *str = @"end_rownum";
    NSDictionary *dic = @{@"transDocId":self.transDocId,
                          @"transBlockId":self.transBlockId,
                          @"transDocName":self.transDocName,
                          @"userType":self.userType,
                          @"userId":[NSString stringWithFormat:@"%d",-1],
                          @"completeDate":[NSString stringWithFormat:@"%@",self.endTimeSub.text],
                          @"projectId":shareData.product_Id,
                          @"teamId":shareData.team_Id,
                          str:self.end_rownum};
    [AvailableNetWorking postWithUrl:assignTask_connector params:dic successHandler:^(id responseObject) {
        
        NSLog(@"dic -- -%@",dic);
        if ([responseObject[@"code"] integerValue] == 200) {
            //退栈并通知刷新上一个界面
            [self.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"AssignTaskSuccessAndRef" object:nil];
        }else{
            
            NSLog(@"-----%@",responseObject[@"message"]);
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"操作失败" andTitleColor:[UIColor whiteColor] andCancel:NO];
        }
        
    } falureHandler:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark -- notification
- (void)hideCoverCliced:(NSNotification *)notification{

    NSLog(@"notification.object --- %@",notification.object);
    _endtimePost = notification.object;
    [self.endTime setTitleEdgeInsets:UIEdgeInsetsMake(-13, 0, 0, 0)];
    self.endTime.titleLabel.font = [UIFont systemFontOfSize:FLEXIBLE(12)];
    self.endTimeSub.text = [NSString stringWithFormat:@"%@",notification.object];
    [self.endTime addSubview:self.endTimeSub];
    _hasEndTime = YES;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.coverView.frame = CGRectMake(0, 64, Screen_Width, 0);
        
    } completion:^(BOOL finished) {
        
    }];
    
    //判断是否选择译员
    if (_lastPath.row >= 0) {
        [self allowToAssignTask];
    }

}

- (void)allowToAssignTask{

    //如果选定了译员 就可以分派任务了
    self.assignTask.backgroundColor = RGB(57,186, 241, 1);
    [self.assignTask setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.assignTask setEnabled:YES];
}

- (void)notAllowAssignTask{
    
    self.assignTask.backgroundColor = RGB(237,239, 240, 1);
    [self.assignTask setTitleColor:RGB(149, 163, 175, 1) forState:UIControlStateNormal];
    [self.assignTask setEnabled:NO];
    
}


#pragma mark -- 根据uiserID获取位置

- (NSIndexPath *)getRowNumberByUserId:(NSInteger)userId andData:(NSMutableArray *)data{

    [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([((AssignModel *)obj).userId integerValue] == userId) {
            _selectedIndex_TransLater = idx;
            _lastPath = [NSIndexPath indexPathForRow:_selectedIndex_TransLater inSection:0];
        }
    }];
    
    return _lastPath;
}

#pragma mark -- 隐藏空白cell的分割线
-(void)setExtraCellLineHidden: (UITableView *)tableView{
    
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}


- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"暂无相关人员" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#666666"]}];
    return str;
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    
    return [UIImage imageNamed:@"任务"];
}

#pragma mark -- getter

- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 55, Screen_Width, Screen_Height - 55 - 60) style:UITableViewStylePlain];
        _tableView.backgroundColor = RGB(250, 250, 250, 1);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.emptyDataSetSource = self;
    }
    return _tableView;
}

- (UIButton *)endTime{
    
    if (!_endTime) {
        _endTime = [UIButton buttonWithType:UIButtonTypeCustom];
        _endTime.frame = CGRectMake(15, Screen_Height-50-64, 140*Radio, 40);
        _endTime.backgroundColor = [UIColor whiteColor];
        [_endTime setTitleColor:RGB(51, 51, 51, 1) forState:UIControlStateNormal];
        [_endTime setTitle:@"设置截止时间" forState:UIControlStateNormal];
        _endTime.layer.cornerRadius = 5;
        _endTime.layer.borderColor = [UIColor colorWithWhite:0.8 alpha:1].CGColor;
        _endTime.layer.borderWidth = 1.f;
        [_endTime addTarget:self action:@selector(endTimeClicked) forControlEvents:UIControlEventTouchUpInside];
        [_endTime setImage:[UIImage imageNamed:@"time_end"] forState:UIControlStateNormal];
        _endTime.imageEdgeInsets = UIEdgeInsetsMake(0,-15,0,0);
        _endTime.titleLabel.font = [UIFont systemFontOfSize:FLEXIBLE(13)];
    }
    return _endTime;
}

- (UIButton *)assignTask{
    
    if (!_assignTask) {
        _assignTask = [UIButton buttonWithType:UIButtonTypeSystem];
        _assignTask.frame = CGRectMake(_endTime.frame.origin.x+_endTime.frame.size.width+10, Screen_Height-50-64, Screen_Width-15-_endTime.frame.size.width-10-15, 40);
        _assignTask.backgroundColor = RGB(237,239, 240, 1);
        [_assignTask setTitleColor:RGB(149, 163, 175, 1) forState:UIControlStateNormal];
        [_assignTask setTitle:@"立即分派" forState:UIControlStateNormal];
        _assignTask.layer.cornerRadius = 5;
        [_assignTask addTarget:self action:@selector(assignTaskClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_assignTask setEnabled:NO];
    }
    return _assignTask;
}

- (UIView *)line{
    
    if (!_line) {
        _line = [[UIView alloc]initWithFrame:CGRectMake(0, Screen_Height-60, Screen_Width, 1)];
        _line.backgroundColor = RGB(236, 236, 236, 1);
    }
    return _line;
}

- (UIView *)coverView{

    if (!_coverView) {
        _coverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, 0)];
        _coverView.backgroundColor = RGB(0, 0, 0, 0.4);
    }
    return _coverView;
}

- (UILabel *)endTimeLabel{

    if (!_endTimeLabel) {
        _endTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, Screen_Height-85*Radio-64, Screen_Width, 25*Radio)];
        _endTimeLabel.backgroundColor = RGB(240, 240, 240, 1);
        _endTimeLabel.textColor = [UIColor colorWithHexString:@"#666666"];
        _endTimeLabel.font = [UIFont systemFontOfSize:FLEXIBLE(13)];
        _endTimeLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _endTimeLabel;
}

- (UILabel *)endTimeSub{

    if (!_endTimeSub) {
        _endTimeSub = [[UILabel alloc]initWithFrame:CGRectMake(_endTime.titleLabel.frame.origin.x-8*Radio, _endTime.titleLabel.frame.origin.y+_endTime.titleLabel.frame.size.height-8*Radio, _endTime.titleLabel.frame.size.width+20*Radio, 16*Radio)];
        _endTimeSub.backgroundColor = [UIColor clearColor];
        _endTimeSub.textColor = mainColor;
        _endTimeSub.font = [UIFont systemFontOfSize:FLEXIBLE(10)];
        _endTimeSub.textAlignment = NSTextAlignmentCenter;
    }
    return _endTimeSub;
}

@end
